﻿using DocumentFormat.OpenXml.Spreadsheet;
using Elasticsearch.Net;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Process;
using NP.BPMReportPlatform.HR.Dto;
using NP.BPMReportPlatform.Leave.Dto;
using NP.BPMReportPlatform.Utilities;
using NP.Enterprise.Utils.Http;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using static NP.BPMReportPlatform.Leave.Dto.LeaveDto;

namespace NP.BPMReportPlatform.Leave
{
    /// <summary>
    /// 请休假接口
    /// </summary>
    public class LeaveService : BPMReportPlatformAppService, ILeaveService
    {
        #region Variables

        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly string _esbSAPUrl;
        private readonly ICommonService _commonService;
        private readonly IExcelImporter _importer;

        #endregion

        #region Constructor

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public LeaveService(ISqlSugarAppService sqlSugarAppService,
            INPRestHttpHelper nPRestHttp, IConfiguration configuration, ICommonService commonService, IExcelImporter importer)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _nPRestHttp = nPRestHttp;
            _esbSAPUrl = configuration["Nippon:ESB:SYQ_ESB_ERPHR_API"];
            _commonService = commonService;
            _importer = importer;
        }

        #endregion


        /// <summary>
        /// 请休假查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetLeaveResultOutput>> GetLeaveResult(GetLeaveResultInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = new List<GetLeaveResultOutput>();
            // 权限过滤
            var role = getLeaveUserRoles();
            int pushStatus = 0;
            if (!string.IsNullOrEmpty(input.PushStatus))
            {
                pushStatus = int.Parse(input.PushStatus);
            }

            if (!string.IsNullOrEmpty(input.ProcessType) && input.ProcessType.ToLower() == "cancelleave")
            {
                listQueryable = await _db.Queryable<LeaveCancelEntity, LeaveEntity, LeaveCancelDetailEntity>(
                    (c, t, d) => c.LeaveInstanceNumber == t.InstanceNumber && c.Id == d.LeaveCancelId)
                    .WhereIF(!input.InstanceNumber.IsNullOrEmpty(), (c, t, d) => c.InstanceNumber == input.InstanceNumber)
                    .WhereIF(!input.WorkNumber.IsNullOrEmpty(), (c, t, d) => t.WorkNumber.Contains(input.WorkNumber))
                    .WhereIF(!input.UserName.IsNullOrEmpty(), (c, t, d) => t.UserName.Contains(input.UserName))
                    .WhereIF(input.StartDate != null, (c, t, d) => input.StartDate <= t.CreateTime)
                    .WhereIF(input.EndDate != null, (c, t, d) => input.EndDate >= t.CreateTime)
                    .WhereIF(input.Department != null, (c, t, d) => t.OrganizationName.Contains(input.Department))
                    .WhereIF(input.UseAdmin != true, (c, t, d) => t.WorkNumber == CurrentUser.UserName)
                    .WhereIF(!role.Item1, (c, t, d) => SqlFunc.ContainsArray(role.Item2, t.WorkNumber))
                    .WhereIF(!string.IsNullOrEmpty(input.PushStatus), (c, t, d) => c.PushStatus == pushStatus)
                    .WhereIF(input.Status != null, (c, t, d) => c.Status == input.Status)
                    .WhereIF(input.LeaveStartDate != null, (c, t, d) =>
                        input.LeaveStartDate <= SqlFunc.ToDate(SqlFunc.MergeString(d.StartDate, " ", d.StartTime)) ||
                        input.LeaveStartDate <= SqlFunc.ToDate(SqlFunc.MergeString(d.EndDate, " ", d.EndTime)))
                    .WhereIF(input.LeaveEndDate != null, (c, t, d) =>
                        input.LeaveEndDate >= SqlFunc.ToDate(SqlFunc.MergeString(d.StartDate, " ", d.StartTime)) ||
                        input.LeaveEndDate >= SqlFunc.ToDate(SqlFunc.MergeString(d.EndDate, " ", d.EndTime)))
                    .WhereIF(!string.IsNullOrEmpty(input.LeaveType), (c, t, d) => t.LeaveType == input.LeaveType)
                    .OrderBy((c, t, d) => c.CreateTime, OrderByType.Desc)
                .Select((c, t, d) => new GetLeaveResultOutput()
                {
                    ApplyerJob = t.ApplyerJob,
                    Id = c.Id,
                    InstanceNumber = c.InstanceNumber,
                    ApplyerTitle = t.ApplyerTitle,
                    CreateTime = t.CreateTime,
                    LeaveType = t.LeaveType,
                    LeaveTypeName = t.LeaveTypeName,
                    OrganizationName = t.OrganizationName,
                    PushDate = c.PushDate,
                    PushErrorMsg = c.PushErrorMsg,
                    PushStatus = c.PushStatus,
                    PushStatusName = c.PushStatusName,
                    Status = c.Status,
                    StatusName = c.StatusName,
                    UserName = t.UserName,
                    WorkNumber = t.WorkNumber,
                    ParentInstanceNumber = t.InstanceNumber,
                    StartDate = d.StartDate,
                    StartTime = d.StartTime,
                    EndDate = d.EndDate,
                    EndTime = d.EndTime,

                }).ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            }
            else
            {
                listQueryable = await _db.Queryable<LeaveEntity, LeaveDetailEntity>((t, b) => t.Id == b.LeaveId)
                    .WhereIF(!input.InstanceNumber.IsNullOrEmpty(), (t, b) => t.InstanceNumber == input.InstanceNumber)
                    .WhereIF(!input.WorkNumber.IsNullOrEmpty(), (t, b) => t.WorkNumber.Contains(input.WorkNumber))
                    .WhereIF(!input.UserName.IsNullOrEmpty(), (t, b) => t.UserName.Contains(input.UserName))
                    .WhereIF(input.StartDate != null, (t, b) => input.StartDate <= t.CreateTime)
                    .WhereIF(input.EndDate != null, (t, b) => input.EndDate >= t.CreateTime)
                    .WhereIF(input.Department != null, (t, b) => t.OrganizationName.Contains(input.Department))
                    .WhereIF(input.UseAdmin != true, (t, b) => t.WorkNumber == CurrentUser.UserName)
                    .WhereIF(!role.Item1, (t, b) => SqlFunc.ContainsArray(role.Item2, t.WorkNumber))
                    .WhereIF(!string.IsNullOrEmpty(input.PushStatus), t => t.PushStatus == pushStatus)
                    .WhereIF(input.Status != null, (t, b) => t.Status == input.Status)
                    .WhereIF(input.LeaveStartDate != null && input.LeaveEndDate != null, (t, b) =>
                        input.LeaveStartDate <= SqlFunc.ToDate(SqlFunc.MergeString(b.StartDate, " ", b.StartTime)) ||
                        input.LeaveStartDate <= SqlFunc.ToDate(SqlFunc.MergeString(b.EndDate, " ", b.EndTime)))
                    .WhereIF(input.LeaveEndDate != null, (t, b) =>
                        input.LeaveEndDate >= SqlFunc.ToDate(SqlFunc.MergeString(b.StartDate, " ", b.StartTime)) ||
                        input.LeaveEndDate >= SqlFunc.ToDate(SqlFunc.MergeString(b.EndDate, " ", b.EndTime)))
                    .WhereIF(!string.IsNullOrEmpty(input.LeaveType), (t, b) => t.LeaveType == input.LeaveType)
                .Select((t, b) =>new GetLeaveResultOutput()
                {
                    ApplyerJob = t.ApplyerJob,
                    Id = t.Id,
                    InstanceNumber = t.InstanceNumber,
                    ApplyerTitle = t.ApplyerTitle,
                    CreateTime = t.CreateTime,
                    LeaveType = t.LeaveType,
                    LeaveTypeName = t.LeaveTypeName,
                    OrganizationName = t.OrganizationName,
                    PushDate = t.PushDate,
                    PushErrorMsg = t.PushErrorMsg,
                    PushStatus = t.PushStatus,
                    PushStatusName = t.PushStatusName,
                    Status = t.Status,
                    StatusName = t.StatusName,
                    UserName = t.UserName,
                    WorkNumber = t.WorkNumber,
                    StartDate = b.StartDate,
                    StartTime = b.StartTime,
                    EndDate = b.EndDate,
                    EndTime = b.EndTime
                }).OrderBy(t => t.CreateTime, OrderByType.Desc)
                .ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            }

            //返回结果
            return new PagedResultDto<GetLeaveResultOutput>()
            {
                TotalCount = totalCount,
                Items = listQueryable
            };
        }

        /// <summary>
        /// 导出请休假
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<MemoryStream> ExportLeaveResultAsync(GetLeaveResultInput input)
        {
            input.PageSize = int.MaxValue;
            var data = await GetLeaveResult(input);
            var fs = File.OpenRead(Environment.CurrentDirectory + "/wwwroot/excel/请休假汇总表.xlsx");
            IWorkbook workbook = new XSSFWorkbook(fs);
            ISheet sheet = workbook.GetSheetAt(0);
            #region // 边框样式

            // 全局样式
            ICellStyle borderStyle = workbook.CreateCellStyle();
            borderStyle.BorderLeft = BorderStyle.Thin;
            borderStyle.BorderRight = BorderStyle.Thin;
            borderStyle.BorderTop = BorderStyle.Thin;
            borderStyle.BorderBottom = BorderStyle.Thin;
            #endregion

            for (int i = 0; i < data.Items.Count; i++)
            {
                List<string> columns = new List<string>();
                columns.Add(data.Items[i].InstanceNumber);
                columns.Add(data.Items[i].WorkNumber);
                columns.Add(data.Items[i].UserName);
                columns.Add(data.Items[i].OrganizationName);
                columns.Add(data.Items[i].CreateTime.ToString("yyyy-MM-dd"));
                columns.Add(data.Items[i].ApplyerJob);
                columns.Add(data.Items[i].ApplyerTitle);
                columns.Add(data.Items[i].LeaveTypeName);
                columns.Add(data.Items[i].StartDate);
                columns.Add(data.Items[i].StartTime);
                columns.Add(data.Items[i].EndDate);
                columns.Add(data.Items[i].EndTime);
                columns.Add(data.Items[i].StatusName);
                columns.Add(data.Items[i].PushStatusName);
                columns.Add(data.Items[i].PushDate.HasValue ? data.Items[i].PushDate?.ToString("yyyy-MM-dd") : string.Empty);
                columns.Add(data.Items[i].PushErrorMsg);
                IRow row = sheet.CreateRow(i + 1);
                for (int j = 0; j < columns.Count; j++)
                {
                    ICell cell = row.CreateCell(j);
                    cell.SetCellValue(columns[j]);
                    cell.CellStyle = borderStyle;
                }
            }

            MemoryStream memoryStream = new MemoryStream();
            workbook.Write(memoryStream);
            workbook.Close();
            return memoryStream;
        }

        /// <summary>
        /// SAP补推
        /// </summary>
        /// <param name="instanceNumber"></param>
        /// <param name="processType"></param>
        /// <returns></returns>
        public async Task<string> PushSAPAsync([FromBody] string instanceNumber, string processType)
        {
            try
            {
                if (processType.ToLower() == "leave")
                {
                    return PushLeaveToSAP(instanceNumber);
                }
                else if (processType.ToLower() == "cancelleave")
                {
                    return PushCancelLeaveToSAP(instanceNumber);
                }
            }
            catch (Exception ex)
            {

                return ex.Message;
            }

            return string.Empty;
        }

        #region 特殊审批流配置

        /// <summary>
        /// 特殊审批人信息查询
        /// </summary>
        /// <param name="input"></param>
        public async Task<PagedResultDto<LeaveSpecialApproverEntity>> GetSpecialApproverAsync(GetSpecialLeaveResultInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = await _db.Queryable<LeaveSpecialApproverEntity>()
                .WhereIF(!input.UserName.IsNullOrEmpty(), t => t.WorkNumber.Contains(input.UserName) || t.UserName.Contains(input.UserName))
                .WhereIF(!input.ApproverName.IsNullOrEmpty(), t =>
                t.Approver1Code.Contains(input.ApproverName) || t.Approver1Name.Contains(input.ApproverName) ||
                t.Approver2Code.Contains(input.ApproverName) || t.Approver2Name.Contains(input.ApproverName) ||
                t.Approver3Code.Contains(input.ApproverName) || t.Approver3Name.Contains(input.ApproverName) ||
                t.Approver4Code.Contains(input.ApproverName) || t.Approver4Name.Contains(input.ApproverName))
                 .ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //返回结果
            return new PagedResultDto<LeaveSpecialApproverEntity>()
            {
                TotalCount = totalCount,
                Items = listQueryable
            };

        }

        /// <summary>
        /// 审批信息导入 导入Excel
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<ImportResultExt<SpecialApproverDto.ImportInput>> ImporterExcelAsync(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            var rst = await _importer.Import<SpecialApproverDto.ImportInput>(stream);
            var importData = rst.Data;
            if (!rst.HasError)
            {
                // 业务数据处理
                var details = _db.Queryable<LeaveSpecialApproverEntity>().ToList();
                List<LeaveSpecialApproverEntity> addList = new List<LeaveSpecialApproverEntity>(); // 新增的证书集合
                List<LeaveSpecialApproverEntity> editList = new List<LeaveSpecialApproverEntity>(); // 更新的证书集合
                // 获取基础连带数据
                foreach (var item in importData)
                {
                    var data = new LeaveSpecialApproverEntity()
                    {
                        Id = Guid.NewGuid().ToString(),
                        WorkNumber = item.WorkNumber,
                        UserName = item.UserName,
                        Approver1Code = item.Approver1Code,
                        Approver1Name = item.Approver1Name,
                        Approver2Code = item.Approver2Code,
                        Approver2Name = item.Approver2Name,
                        Approver3Code = item.Approver3Code,
                        Approver3Name = item.Approver3Name,
                        Approver4Code = item.Approver4Code,
                        Approver4Name = item.Approver4Name,
                    };

                    var oldDetail = details.Where(x => x.WorkNumber == item.WorkNumber.Trim()).FirstOrDefault();
                    if (oldDetail == null)
                    {
                        addList.Add(data);
                    }
                    else
                    {
                        data.Id = oldDetail.Id;
                        editList.Add(data);
                    }
                }
                if (addList.Count > 0)
                {
                    await _db.Insertable(addList).ExecuteCommandAsync();
                }
                if (editList.Count > 0)
                {
                    await _db.Updateable(editList).ExecuteCommandAsync();
                }
            }
            var resp = new ImportResultExt<SpecialApproverDto.ImportInput>()
            {
                Data = importData,
                Exception = rst.Exception,
                RowErrors = rst.RowErrors,
                TemplateErrors = rst.TemplateErrors
            };
            return resp;
        }

        /// <summary>
        /// 保存审批配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task EditAsync(LeaveSpecialApproverEntity input)
        {
            if (input != null)
            {
                await _db.Updateable(input).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 删除审批配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                await _db.Deleteable<LeaveSpecialApproverEntity>().Where(t => t.Id == id).ExecuteCommandAsync();
            }
        }

        #endregion

        private string PushLeaveToSAP(string instanceNumber)
        {
            var leave = _db.Queryable<LeaveEntity>().Where(t => t.InstanceNumber == instanceNumber).First();
            if (leave == null || leave.PushStatus == 1)
            {
                throw new Exception("数据有误，请不要再次推送SAP");
            }

            // 明细
            List<LeaveDetailEntity> details = _db.Queryable<LeaveDetailEntity>().Where(t => t.LeaveId == leave.Id).ToList();

            // 将结果 推送给SAP
            var checkData = PushSAP(leave, details);
            if (checkData.ZOA_HR_ABSENCE_CREATEResponse.FLAG == "X")
            {
                var pushData = PushSAP(leave, details, false);
                if (pushData.ZOA_HR_ABSENCE_CREATEResponse.FLAG == "X")
                {
                    leave.PushStatus = 1;
                    leave.PushStatusName = "已确认";
                    leave.PushDate = DateTime.Now;
                    leave.PushErrorMsg = pushData.ZOA_HR_ABSENCE_CREATEResponse.ERR_MSG;
                }
                else
                {
                    var messagelist = pushData.ZOA_HR_ABSENCE_CREATEResponse?.OA_HR_ABSENCE?.item?
                        .Where(t => !string.IsNullOrEmpty(t.MESSAGE)).Select(t => t.MESSAGE).ToList();

                    leave.PushStatus = -1;
                    leave.PushDate = DateTime.Now;
                    leave.PushStatusName = "推送失败";
                    leave.PushErrorMsg = pushData.ZOA_HR_ABSENCE_CREATEResponse.ERR_MSG
                               + "[" + string.Join("|||", messagelist) + "]";
                }
            }
            else
            {
                var messagelist = checkData.ZOA_HR_ABSENCE_CREATEResponse?.OA_HR_ABSENCE?.item?
                        .Where(t => !string.IsNullOrEmpty(t.MESSAGE)).Select(t => t.MESSAGE).ToList();
                leave.PushStatus = -1;
                leave.PushDate = DateTime.Now;
                leave.PushStatusName = "校验失败";
                leave.PushErrorMsg = checkData.ZOA_HR_ABSENCE_CREATEResponse.ERR_MSG
                                + "[" + string.Join("|||", messagelist) + "]";
            }

            _db.Updateable(leave).UpdateColumns(t => new { t.PushStatusName, t.PushDate, t.PushErrorMsg, t.PushStatus }).ExecuteCommand();

            return leave.PushErrorMsg;
        }

        private LeaveDto.LeavePushResponse PushSAP(LeaveEntity leave, List<LeaveDetailEntity> details, bool isCheck = true)
        {
            // 请假信息推送给SAP
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "serviceName", "S_Gaia_ERPHR_ZorHrAbsence_S" },
                { "sourceSystem", "BPMNEW" }
            };
            LeaveDto.LeavePushResponse result = new LeaveDto.LeavePushResponse()
            {
                ZOA_HR_ABSENCE_CREATEResponse = new LeaveDto.CREATEResponse()
            };

            try
            {
                var requestBody = new LeaveDto.LeavePushRequestDto()
                {
                    ZOA_HR_ABSENCE_CREATE = new LeaveDto.LeavePushData()
                    {
                        ABSENCETYPE = leave.LeaveType,
                        EMPLOYEENUMBER = leave.WorkNumber,
                        SIMULATE = isCheck ? "X" : string.Empty,
                        OA_HR_ABSENCE = new LeaveDto.OA_HR_ABSENCE()
                        {
                            item = details.Select(t => new LeaveDto.OA_HR_ABSENCEData()
                            {
                                VALIDITYBEGIN = t.StartDate,
                                START = t.StartTime + ":00",
                                VALIDITYEND = t.EndDate,
                                END = t.EndTime + ":00"
                            }).ToList()
                        }
                    }
                };

                var resultData = _nPRestHttp.ESBPostAsync(_esbSAPUrl, requestBody, dic).Result;
                result = JsonConvert.DeserializeObject<LeaveDto.LeavePushResponse>(resultData);
            }
            catch (Exception e)
            {
                result.ZOA_HR_ABSENCE_CREATEResponse.ERR_MSG = e.Message;
            }

            return result;
        }

        private string PushCancelLeaveToSAP(string instanceNumber)
        {
            var cancelleave = _db.Queryable<LeaveCancelEntity>().Where(t => t.InstanceNumber == instanceNumber).First();
            if (cancelleave == null || cancelleave.PushStatus == 1)
            {
                throw new Exception("数据有误，请不要再次推送SAP");
            }

            var leave = _db.Queryable<LeaveEntity>().Where(t => t.InstanceNumber == cancelleave.LeaveInstanceNumber).First();

            if (leave == null)
            {
                throw new Exception("未找到对应的请假流程");
            }

            // 明细
            List<LeaveCancelDetailEntity> details = _db.Queryable<LeaveCancelDetailEntity>().Where(t => t.LeaveCancelId == cancelleave.Id).ToList();
            var checkData = PushCancelSAP(leave, details);
            if (checkData?.ZHR_ABSENCE_DELEResponse?.OUTPUT?.ZMT_ABSENCE_RESP?.FLAG == "S")
            {
                var pushData = PushCancelSAP(leave, details, false);
                if (pushData?.ZHR_ABSENCE_DELEResponse?.OUTPUT?.ZMT_ABSENCE_RESP?.FLAG == "S")
                {
                    cancelleave.PushStatus = 1;
                    cancelleave.PushStatusName = "已确认";
                    cancelleave.PushDate = DateTime.Now;
                    cancelleave.PushErrorMsg = pushData?.ZHR_ABSENCE_DELEResponse?.OUTPUT?.ZMT_ABSENCE_RESP?.ERR_MSG;
                }
                else
                {
                    cancelleave.PushStatus = -1;
                    cancelleave.PushDate = DateTime.Now;
                    cancelleave.PushStatusName = "推送失败";
                    cancelleave.PushErrorMsg = pushData?.ZHR_ABSENCE_DELEResponse?.OUTPUT?.ZMT_ABSENCE_RESP?.ERR_MSG;
                }
            }
            else
            {
                cancelleave.PushStatus = -1;
                cancelleave.PushDate = DateTime.Now;
                cancelleave.PushStatusName = "校验失败";
                cancelleave.PushErrorMsg = checkData?.ZHR_ABSENCE_DELEResponse?.OUTPUT?.ZMT_ABSENCE_RESP?.ERR_MSG;
            }

            _db.Updateable(cancelleave).UpdateColumns(t => new { t.PushStatusName, t.PushDate, t.PushErrorMsg, t.PushStatus }).ExecuteCommand();

            return cancelleave.PushErrorMsg;
        }

        private LeaveDto.LeaveCancelPushResponse PushCancelSAP(LeaveEntity leave, List<LeaveCancelDetailEntity> details, bool isCheck = true)
        {
            // 请假信息推送给SAP
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "serviceName", "S_Gaia_ERPHR_ZhrAbsenceDele_S" },
                { "sourceSystem", "BPMNEW" }
            };
            LeaveDto.LeaveCancelPushResponse result = new LeaveDto.LeaveCancelPushResponse()
            {
                ZHR_ABSENCE_DELEResponse = new LeaveCancelResponse()
                {
                    OUTPUT = new LeaveCancelOUTPUT()
                    {
                        ZMT_ABSENCE_RESP = new ZMT_ABSENCE_RESP()
                    }
                }
            };

            var controller = new CancelLeavePushRequest();

            controller.item = details.Select(t => new CONTROLLERItem()).ToList();

            try
            {
                var requestBody = new
                {
                    ZHR_ABSENCE_DELE = new
                    {
                        INPUT = new
                        {
                            CONTROLLER = controller,
                            ZMT_ABSENCE_REQ = new
                            {
                                CONTROLLER = controller,
                                ABSENCETYPE = leave.LeaveType,
                                OA_HR_ABSENCE = new
                                {
                                    ITEM = new
                                    {
                                        item = details.Select(t => new
                                        {
                                            VALIDITYBEGIN = t.StartDate,
                                            START = t.StartTime + ":00",
                                            VALIDITYEND = t.EndDate,
                                            END = t.EndTime + ":00",
                                            CONTROLLER = controller
                                        }).ToList()
                                    },
                                    CONTROLLER = controller
                                },
                                EMPLOYEENUMBER = leave.WorkNumber,
                                SIMULATE = isCheck ? "X" : string.Empty,
                            }
                        },
                    }
                };

                var resultData = _nPRestHttp.ESBPostAsync(_esbSAPUrl, requestBody, dic).Result;
                result = JsonConvert.DeserializeObject<LeaveDto.LeaveCancelPushResponse>(resultData);
            }
            catch (Exception e)
            {
                result.ZHR_ABSENCE_DELEResponse.OUTPUT.ZMT_ABSENCE_RESP.ERR_MSG = e.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, List<string>> getLeaveUserRoles()
        {
            // 权限过滤
            var currentWorkNumber = CurrentUser != null && CurrentUser.UserName != null ? CurrentUser.UserName : string.Empty;
            var userCodes = _commonService.GetUserByRoleFilter(currentWorkNumber, RelationshipTypeEnum.ER);
            userCodes = userCodes != null && userCodes.Count > 0 ? userCodes : new List<string>() { "-1" };
            bool isAdmin = userCodes.Contains("9999999999");
            if (isAdmin)
            {
                return new Tuple<bool, List<string>>(isAdmin, userCodes);
            }
            else
            {
                var userCodes1 = _commonService.GetUserByRoleFilter(currentWorkNumber, RelationshipTypeEnum.HRBP);
                if (userCodes1 != null && userCodes1.Count() > 0)
                {
                    userCodes.AddRange(userCodes1);
                    userCodes = userCodes.Distinct().ToList();
                }
            }
            return new Tuple<bool, List<string>>(isAdmin, userCodes);
        }
    }
}